package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpExprService empExprService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        this.save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            //添加
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    public Emp findById(Integer id) {
        //直接有根据id查询的方法
        Emp byId = this.getById(id);
        //根据id查询出员工的经历
        LambdaQueryWrapper<EmpExpr> empLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empLambdaQueryWrapper.eq(EmpExpr::getEmpId, id);
        List<EmpExpr> list = empExprService.list(empLambdaQueryWrapper);
        byId.setExprList(list);
        return byId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        //修改员工
        this.updateById(emp);
        //删除经历，根据员工id来删除
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        //新增经历
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            //设置新的员工id
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            //新增
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> ids) {
        //先删除员工
        this.removeByIds(ids);
        //在删除经历
        //条件删除,sql:delete from empexpr where emp_id in(1,2,3)
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }
}
